/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package memsim;
/**
 *
 * @author Mankin
 */
public class Floats {

    //final String POS_ZERO = "00000000000000000000000000000000";
    //final String NEG_ZERO = "10000000000000000000000000000000";

    final static String ZERO_SIG = "00000000000000000000000";
    final static String ZERO_EXP = "00000000";
    final static String MAX_EXP = "11111111";
    final static char NEGATIVE = '1';
    final static char POSITIVE = '0';


    public static String toFloat(long value)
    {
         String binaryString = Long.toBinaryString(value);

        //leading zeros, make sure they're there
        while(binaryString.length() < 32)
        {
            binaryString = "0" + binaryString;
        }

        char signedBit = binaryString.charAt(0);
        String exponent = binaryString.substring(1, 9);
        String significand = binaryString.substring(9);
        int exp = Integer.parseInt(exponent, 2);

        //
        if(exponent.equals(ZERO_EXP))
        {
            if(significand.equals(ZERO_SIG))
            {
                if(signedBit == NEGATIVE)
                {
                    return "-0.0f";
                }
                else
                {
                    return "0.0f";
                }
            }
            else
            {
                exp = 1;
                significand = "0" + significand;
            }
        }
        else if(exponent.equals(MAX_EXP))
        {
            if(significand.equals(ZERO_SIG))
            {
                if(signedBit == NEGATIVE)
                {
                    return "-inf";
                }
                else
                {
                    return "inf";
                }
            }
            else
            {
                //neg or pos would determine quiet vs signaling NaN
                return "NaN";
            }
        }
        else
        {
            significand = "1" + significand;
        }
        //if normalized, add "1" to most sig digit

        //decode
        
        exp -= 127;

        float curFrac = 1;
        float sumFrac = 0;
        for(int i = 0; i < significand.length(); i++)
        {
            if(significand.charAt(i) == '1')
            {
                sumFrac += curFrac;
            }
            curFrac = curFrac / 2;
        }
        float tempFloat = (float)Math.pow(2, exp);
        float finalFloat = sumFrac * tempFloat;

        if(signedBit == '1')
            finalFloat = finalFloat * -1.0f;

        System.out.println(finalFloat);
        return Float.toString(finalFloat) + "f";
    }

}
